// pages/login/login.js
const host=getApp().host;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loginName:'',
    passWord:'',
    key:'',
    captcha:'',
    verCode:''
  },

  /**初始化验证码 */
  initCaptcha(){
    wx.request({
      url: host+'/admin/login/captcha',
      success:res=>{
        if(res.data.status.code==204){
          wx.showModal({
            title: '提示',
            content: '获取验证码失败',
            showCancel:false,
            confirmText:'重新获取',
            success:()=>{
              this.initCaptcha()
            }
          })
        }else{
          this.setData({
            key:res.data.data.key,
            captcha:res.data.data.captcha
          })
        }
      }
    })
  },

  /**登录 */
  login(e){
    console.log(e);
    wx.showLoading({
      title: '正在登录',
    })
    wx.request({
      url: host+'/admin/login',
      method:'POST',
      header:{
        'content-type': 'application/x-www-form-urlencoded'
      },
      data:{
        username:this.data.loginName,
        password:this.data.passWord,
        key:this.data.key,
        verCode:this.data.verCode
      },
      success:res=>{
        if(res.data.status.code==200){
              wx.setStorageSync('avatar', e.detail.userInfo.avatarUrl);
              wx.setStorageSync('token',res.data.data.token);
              wx.setStorageSync('admin',res.data.data.admin);
              wx.setStorageSync('role',res.data.data.roles[0]);
              if(res.data.data.roles[0].id==4){
                this.initUserInfo(res.data.data.admin.loginName)
              }else{
                wx.navigateBack()
                wx.showToast({
                  title: '登录成功',
                  icon:'success'
                })
              }

        }else{
          console.log(res);
          wx.showToast({
            title: '登录失败',
            icon:'none'
          })
          this.initCaptcha();
        }
      }
    })
  },
  
  /**初始化学生信息 */
  initUserInfo(loginName){
    wx.request({
      url: host+'/client/userInfo?user='+loginName,
      success:res=>{
        wx.setStorageSync('userInfo', res.data.data.info)
        wx.navigateBack()
        wx.showToast({
          title: '登录成功',
          icon:'success'
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  toReg(){
    wx.navigateTo({
      url: '/pages/reg/reg',
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.initCaptcha();
  },
  inputName(e){
    this.setData({
      loginName:e.detail.value
    })
  },
  inputPwd(e){
    this.setData({
      passWord:e.detail.value
    })
  },
  inputCaptcha(e){
    this.setData({
      verCode:e.detail.value
    })
  }

})